package com.cc.util;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ThinkGem
 * @version 2013-05-22
 */
public class StringUtils {
	
	public static final String EMPTY = "";
	
    private static final String NULL = "null";
    
	/**
	 * 转换为Double类型
	 */
	public static Double toDouble(String val){
		if (isEmpty(val)){
			return 0D;
		}
		try {
			return Double.valueOf((val.toString()).trim());
		} catch (Exception e) {
			return 0D;
		}
	}

	/**
	 * 转换为Float类型
	 */
	public static Float toFloat(String val){
		return toDouble(val).floatValue();
	}

	/**
	 * 转换为Long类型
	 */
	public static Long toLong(String val){
		return toDouble(val).longValue();
	}

	/**
	 * 转换为Integer类型
	 */
	public static Integer toInteger(String val){
		return toLong(val).intValue();
	}
	
	/**
	 * 获得用户远程地址
	 */
	public static String getRemoteAddr(HttpServletRequest request){
		String remoteAddr = request.getHeader("X-Real-IP");
        if (!isEmpty(remoteAddr)) {
        	remoteAddr = request.getHeader("X-Forwarded-For");
        }else if (!isEmpty(remoteAddr)) {
        	remoteAddr = request.getHeader("Proxy-Client-IP");
        }else if (!isEmpty(remoteAddr)) {
        	remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
	}

    /**
     * 如果不为空，则设置值
     * @param target
     * @param source
     */
    public static void setValueIfNotBlank(String target, String source) {
		if (!isEmpty(source)){
			target = source;
		}
	}
 
    /**
     * 检查字符串是否为 null,"","null"
     * @param s
     * @return
     */
    public static boolean isEmpty(String s){
    	if(s==null || EMPTY.equals(s) || NULL.equals(s)){
    		return true;
    	}
    	return false;
    }
    
    public static String toString(byte[] bs){
    	return bs.toString();
    }

	public static byte[] getBytes(String object) {
		return object.getBytes();
	}
	
	public static int strInArr(String str,String[] arr){
		if(isEmpty(str))
			return -1;
		for (int i=0;i<arr.length;i++) {
			if(str.equals(arr[i]))
				return i;
		}
		return -1;
	}
}
